package com.xw.service.impl;

import com.xw.common.Constants;
import com.xw.dao.RoleMenuDao;
import com.xw.dao.UserDao;
import com.xw.entity.Menu;
import com.xw.entity.RoleMenu;
import com.xw.entity.Roles;
import com.xw.dao.RolesDao;
import com.xw.entity.User;
import com.xw.exp.ServiceException;
import com.xw.rep.RoleByMenuRep;
import com.xw.req.AddRoleMenuReq;
import com.xw.service.MenuService;
import com.xw.service.RolesService;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xw.req.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;


/**
 * @Description: 针对表【roles】的数据库操作Service实现
 * @Author: 72478
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */
@Service("rolesService")
public class RolesServiceImpl implements RolesService {
    @Resource
    private RolesDao rolesDao;

    @Resource
    private RoleMenuDao roleMenuDao;

    @Resource
    private MenuService menuService;

    @Resource
    private UserDao userDao;


    /**
     * 分页查询
     *
     * @return 查询结果
     */

    @Override
    public PageInfo<Roles> queryByPage(PageRequest<Roles> pageRequest) {
        //开始分页
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<Roles> list = this.rolesDao.queryAll(pageRequest.getQ());
        PageInfo<Roles> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public RoleByMenuRep selectRoleByMenu(Integer roleId) {
        List<Integer> checkedKeys = roleMenuDao.selectByRoleId(roleId);
        if (!CollectionUtils.isEmpty(checkedKeys)) {
            checkedKeys = checkedKeys.stream().distinct().collect(Collectors.toList());
        } else {
            checkedKeys = new ArrayList<>();
        }
        List<Menu> menus = menuService.menuList();
        RoleByMenuRep roleByMenuRep = new RoleByMenuRep();
        roleByMenuRep.setMenus(menus);
        for (Menu menu : menus) {
            Optional<Integer> any = checkedKeys.stream().filter(u -> u.compareTo(menu.getId()) == 0).findAny();
            if (any.isPresent() && menu.getParentId() == null && !CollectionUtils.isEmpty(menu.getChildren()) && !StringUtils.hasText(menu.getPath())) {
                checkedKeys.remove(any.get());
            }
        }
        roleByMenuRep.setCheckedKeys(checkedKeys);
        return roleByMenuRep;
    }

    @Override
    @Transactional
    public void addRoleMenu(AddRoleMenuReq addRoleMenuReq) {
        if (CollectionUtils.isEmpty(addRoleMenuReq.getMenuIds())) {
            throw new ServiceException(Constants.ERROR.getCode(), "请选择菜单！");
        }
        List<Integer> roleMenuIds = roleMenuDao.selectByRoleId(addRoleMenuReq.getRoleId());
        if (!CollectionUtils.isEmpty(roleMenuIds)) {
            // 通过角色ID删除所有角色与菜单的关联
            roleMenuDao.deleteByRoleId(addRoleMenuReq.getRoleId());
        }
        // 开始新增角色与菜单的关系
        for (Integer menuId : addRoleMenuReq.getMenuIds()) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(addRoleMenuReq.getRoleId());
            roleMenu.setMenuId(menuId);
            roleMenuDao.insert(roleMenu);
        }
    }

    @Override
    @Transactional
    public void deleteRoleAndHandleRelations(Integer roleId) {
        // 先查询角色是否存在等验证逻辑，省略，可参考之前内容

        Roles roleToDelete = rolesDao.queryById(roleId);
        if (roleToDelete == null) {
            throw new ServiceException(Constants.ERROR.getCode(), "角色不存在");
        }

        // 使用新增的updateUsersRoleToDefault方法更新关联用户的角色为默认角色
        List<User> usersWithThisRole = userDao.findUsersByRole(roleToDelete.getName());
        if (!usersWithThisRole.isEmpty()) {
            int updateCount = userDao.updateUsersRoleToDefault(roleToDelete.getName());
            if (updateCount > 0) {
                // 可以在这里添加日志记录等操作，提示成功更新了多少用户的角色等信息
            } else {
                // 根据业务需求处理更新失败的情况，比如抛出异常或者记录错误日志等
                throw new ServiceException(Constants.ERROR.getCode(), "更新用户角色为默认角色失败");
            }
        }

        // 删除角色菜单关联记录
        roleMenuDao.deleteByRoleId(roleId);

        // 最后删除角色本身记录
        rolesDao.deleteById(roleId);
    }
}
